package org.jeecg.common.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QueryWrapperBuilder {

    /**
     * 根据 SQL 动态构建 QueryWrapper，并支持分页、排序和分组
     *
     * @param sql 查询语句，例如：SELECT * FROM web_teammx WHERE AREAADVISER LIKE '%美国%' AND WORKTIME > 8 GROUP BY AREAADVISER ORDER BY WORKTIME DESC LIMIT 0, 10
     * @param clazz 实体类类型
     * @param <T> 泛型实体类型
     * @return 动态构建的 QueryWrapper 和分页信息
     */
    public static <T> QueryWrapperWithPage<T> build(String sql, Class<T> clazz) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        Page<T> page = null;

        // 解析 WHERE 子句
        String whereRegex = "(?i)WHERE (.+?)(?= GROUP BY| ORDER BY| LIMIT|$)";
        Matcher whereMatcher = Pattern.compile(whereRegex).matcher(sql);

        if (whereMatcher.find()) {
            String whereClause = whereMatcher.group(1).trim();

            // 分割条件（假设条件之间用 AND 连接）
            String[] conditions = whereClause.split("(?i) AND ");

            for (String condition : conditions) {
                parseCondition(condition.trim(), queryWrapper);
            }
        }

        // 解析 GROUP BY 子句
        String groupByRegex = "(?i)GROUP BY (.+?)(?= ORDER BY| LIMIT|$)";
        Matcher groupByMatcher = Pattern.compile(groupByRegex).matcher(sql);

        if (groupByMatcher.find()) {
            String groupByClause = groupByMatcher.group(1).trim();
            String[] groupByFields = groupByClause.split(",");
            for (String field : groupByFields) {
                queryWrapper.groupBy(trim(field));
            }
        }

        // 解析 ORDER BY 子句
        String orderByRegex = "(?i)ORDER BY (.+?)(?= LIMIT|$)";
        Matcher orderByMatcher = Pattern.compile(orderByRegex).matcher(sql);

        if (orderByMatcher.find()) {
            String orderByClause = orderByMatcher.group(1).trim();
            String[] orderByFields = orderByClause.split(",");
            for (String field : orderByFields) {
                if (field.toLowerCase().contains(" desc")) {
                    queryWrapper.orderByDesc(trim(field.replace(" desc", "").replace("DESC", "")));
                } else if (field.toLowerCase().contains(" asc")) {
                    queryWrapper.orderByAsc(trim(field.replace(" asc", "").replace("ASC", "")));
                } else {
                    queryWrapper.orderByAsc(trim(field)); // 默认升序
                }
            }
        }

        // 解析 LIMIT 子句
        String limitRegex = "(?i)LIMIT (\\d+),\\s*(\\d+)";
        Matcher limitMatcher = Pattern.compile(limitRegex).matcher(sql);
        long current = 0;
        long size = 10;
        if (limitMatcher.find()) {
             current = Long.parseLong(limitMatcher.group(1)) / Long.parseLong(limitMatcher.group(2)) + 1;
             size = Long.parseLong(limitMatcher.group(2));

        }

//        boolean hasCount = sql.toLowerCase().contains("count(*)");
//
//        if (hasCount) {
//            // 添加 count() 的功能
//            queryWrapper.select("COUNT(*)");
//        }

        page = new Page<>(current, size);
        return new QueryWrapperWithPage<>(queryWrapper, page);
    }

    /**
     * 解析单个条件并添加到 QueryWrapper
     *
     * @param condition 条件字符串，例如：AREAADVISER LIKE '%美国%' 或 WORKTIME > 8
     * @param queryWrapper QueryWrapper 实例
     */
    private static void parseCondition(String condition, QueryWrapper<?> queryWrapper) {
        if (condition.contains(" LIKE ")) {
            String[] parts = condition.split(" LIKE ");
            queryWrapper.like(trim(parts[0]), trim(parts[1]).replace("'", "").replace("%", ""));
        } else if (condition.contains(" > ")) {
            String[] parts = condition.split(" > ");
            queryWrapper.gt(trim(parts[0]), parseValue(parts[1]));
        } else if (condition.contains(" < ")) {
            String[] parts = condition.split(" < ");
            queryWrapper.lt(trim(parts[0]), parseValue(parts[1]));
        } else if (condition.contains(" = ")) {
            String[] parts = condition.split(" = ");
            queryWrapper.eq(trim(parts[0]), parseValue(parts[1]));
        } else if (condition.contains(" IN ")) {
            String[] parts = condition.split(" IN ");
            String[] values = parts[1].replaceAll("[()]", "").split(",");
            queryWrapper.in(trim(parts[0]), (Object[]) values);
        }
        // 扩展其他操作符
    }

    /**
     * 去除多余空格或引号
     *
     * @param str 输入字符串
     * @return 处理后的字符串
     */
    private static String trim(String str) {
        return str.trim().replace("'", "");
    }

    /**
     * 将字符串解析为对应的数据类型
     *
     * @param value 字符串值
     * @return 转换后的值
     */
    private static Object parseValue(String value) {
        value = value.trim().replace("'", "");
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return value;
        }
    }

    /**
     * 内部类，封装 QueryWrapper 和分页信息
     */
    public static class QueryWrapperWithPage<T> {
        private final QueryWrapper<T> queryWrapper;
        private final Page<T> page;

        public QueryWrapperWithPage(QueryWrapper<T> queryWrapper, Page<T> page) {
            this.queryWrapper = queryWrapper;
            this.page = page;
        }

        public QueryWrapper<T> getQueryWrapper() {
            return queryWrapper;
        }

        public Page<T> getPage() {
            return page;
        }
    }
}
